﻿using QQ群成员获取.Common;
using QQ群成员获取.Model;
using QQ群成员获取.Operate;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;

using System.Windows.Media;

namespace QQ群成员获取.ViewModel
{
    public class MainViewModel:NotifyBase,IExecute
    {
        private FormsWebBrowser _formsWeb;
        private bool bOutload = false;
        private bool bIsLoading = false;
        private int pageIdx = 1;
        private string strCode = "";
        private bool isLoadFinish = false;
        public ObservableCollection<GroupMemberModel> GroupMemberModels { get; set; }
        public ObservableCollection<GruopModel> GroupModels { get; set; }
        public CommandBase GrpChangeCmd { get; set; }

        public CommandBase OutPutCmd { get; set; }
        public bool IsLoadFinish { get => isLoadFinish; set { isLoadFinish = value;this.Notify(); } }

        private GroupInfoManage infoManage = null;
        private Window _window = null;
        public MainViewModel(FormsWebBrowser formsWeb,Window window)
        {
            _formsWeb = formsWeb;
            infoManage = new GroupInfoManage();
            GroupMemberModels = new ObservableCollection<GroupMemberModel>();
            GroupModels = new ObservableCollection<GruopModel>();
            GrpChangeCmd = new CommandBase() {
                actExecute = LoadGrp,
                funcExecute = a => { return true; }
            };
            OutPutCmd = new CommandBase()
            {
                actExecute = OutPut,
                funcExecute = a => { return true; }
            };
            _window = window;
        }

        public void Reset()
        {
            bOutload = false;
            bIsLoading = false;
            pageIdx = 1;
            strCode = "";
            isLoadFinish = false;
            GroupMemberModels.Clear();
            GroupModels.Clear();
        }
        public void OutPut(object obj) {
            infoManage.Init(_formsWeb.WebBrowser.Document.Cookie);
            SolidColorBrush solidClr = System.Windows.Application.Current.Resources.MergedDictionaries[0]["mainColor"] as SolidColorBrush;
            Color color = (Color)ColorConverter.ConvertFromString("#212122");
            if (solidClr != null)
            {
                color = solidClr.Color;
            }
            
            if (string.IsNullOrWhiteSpace(strCode) || GroupMemberModels.Count == 0)
            {
                MessageBoxWindow wind = new MessageBoxWindow(color, "请先登录获取群信息");
                wind.ShowDialog();
                return;
            }
            var saveFileDialog = new System.Windows.Forms.SaveFileDialog();
            saveFileDialog.Filter = "Excel文件|*.xls;*.xlsx";
            if (saveFileDialog.ShowDialog() != System.Windows.Forms.DialogResult.OK)
            {
                return;
            }
            string strName = GroupModels.Where(x => x.Code == strCode).Select(x => x.Name).First();
            string strSavePath = saveFileDialog.FileName;
            //导出之前 将其加载完毕
            if (IsLoadFinish == false)
            {
                ProcessWindow processWindowLoad = new ProcessWindow(color,$"正在加载当前群成员:{strName}({strCode})"
                , this);
                processWindowLoad.Owner = _window;
                processWindowLoad.ShowDialog();
            }
            
            ProcessWindow processWindow = new ProcessWindow(color, $"导出Excel:当前群号-{strCode},导出个数:{GroupMemberModels.Count},目标路径:{strSavePath}"
                ,new ExcelExpotor(strName, GroupMemberModels.ToList(),strSavePath));
            processWindow.Owner = _window;
            processWindow.ShowDialog();
            MessageBoxWindow wind1 = new MessageBoxWindow(color, processWindow.Finished?"导出完成":"导出失败");
            wind1.ShowDialog();
        }
        public void LoadGrp(object obj)
        {
            if (obj == null)
            {
                return;
            }
            infoManage.Init(_formsWeb.WebBrowser.Document.Cookie);
            GruopModel grpModel = obj as GruopModel;
            if (grpModel == null||strCode == grpModel.Code)
            {
                return;
            }
            Load(grpModel.Code);
        }
        public bool LoadGroupInfo(string strHtml)
        {
            if (string.IsNullOrWhiteSpace(strHtml))
            {
                return false;
            }
            infoManage.Init(_formsWeb.WebBrowser.Document.Cookie);
            GroupModels.Clear();
            GroupMemberModels.Clear();
            var grpModellst = infoManage.Parse(strHtml);
            if (grpModellst == null || grpModellst.Count == 0)
            {
                return false;
            }
            grpModellst.ForEach(x => { GroupModels.Add(x); });
            GroupModels[0].IsSelect = true;
            Load(GroupModels[0].Code);
            return true;
        }
        public async Task<bool> LoadGroupInfo()
        {
            GroupModels.Clear();
            GroupMemberModels.Clear();
            var grpModellst = await infoManage.GetGroupModels();
            if (grpModellst == null||grpModellst.Count ==0)
            {
                return false;
            }
            grpModellst.ForEach(x => { GroupModels.Add(x); });
            return true;
        }
        public void ScrollViewerMember_ScrollChanged(object sender, ScrollChangedEventArgs e)
        {
            if (e == null|| bIsLoading)
            {
                return;
            }
            var scrollViewer = e.OriginalSource as ScrollViewer;
            if (e.VerticalOffset != 0 && e.VerticalOffset == scrollViewer.ScrollableHeight)
            {
                if (infoManage.GetMaxCount(pageIdx) > GroupMemberModels.Count)
                {
                    IsLoadFinish = true;
                    return;
                }
                pageIdx++;
                Load(strCode, pageIdx);
            }
        }

        private void Load(object objCode)
        {
            if (objCode == null||string.IsNullOrWhiteSpace(objCode.ToString()))
            {
                return;
            }
            if (strCode == objCode.ToString())
            {
                return;
            }
            IsLoadFinish = false;
            pageIdx = 1;//重置
            GroupMemberModels.Clear();
            Load(objCode.ToString(), pageIdx);
        }

        private async void Load(string _strCode, int iPage)
        {
            int iCountPage = infoManage.PageCount;
            if (bOutload == false)
            {
                GroupMemberModel groupMemberModel = new GroupMemberModel()
                {
                    Nick = "正在加载中...",
                };
                Application.Current.Dispatcher.Invoke(new Action(() =>
                {
                    GroupMemberModels.Add(groupMemberModel);
                }));
            }
            
            bIsLoading = true;

            List<GroupMemberModel> groupMemberModels = null;
            try
            {
                groupMemberModels = await infoManage.GetGroupMemberModels(_strCode, pageIdx);
            }
            catch { 
                
            }
            if (groupMemberModels == null || groupMemberModels.Count == 0)
            {
                if (bOutload == false)
                {
                    Application.Current.Dispatcher.Invoke(new Action(() =>
                    {
                        GroupMemberModels.RemoveAt(GroupMemberModels.Count - 1);
                    }));
                }
                bIsLoading = false;
                return;
            }
            strCode = _strCode;
            Application.Current.Dispatcher.Invoke(new Action(() =>
            {
                if (bOutload == false)
                {
                    GroupMemberModels.RemoveAt(GroupMemberModels.Count - 1);
                }
                groupMemberModels.ForEach(x =>
                {
                    x.Index = GroupMemberModels.Count + 1;
                    GroupMemberModels.Add(x);
                });
                bIsLoading = false;
            }));
            if (GroupMemberModels.Count < infoManage.GetMaxCount(iPage))
            {
                IsLoadFinish = true;
            }
        }

        private void LoadNoAsync(string _strCode, int iPage)
        {
            int iCountPage = infoManage.PageCount;
            if (bOutload == false)
            {
                GroupMemberModel groupMemberModel = new GroupMemberModel()
                {
                    Nick = "正在加载中...",
                };
                Application.Current.Dispatcher.Invoke(new Action(() =>
                {
                    GroupMemberModels.Add(groupMemberModel);
                }));
            }

            bIsLoading = true;

            List<GroupMemberModel> groupMemberModels = infoManage.GetGroupMemberModels(_strCode, pageIdx).Result;
            if (groupMemberModels == null || groupMemberModels.Count == 0)
            {
                if (bOutload == false)
                {
                    Application.Current.Dispatcher.Invoke(new Action(() =>
                    {
                        GroupMemberModels.RemoveAt(GroupMemberModels.Count - 1);
                    }));
                }
                bIsLoading = false;
                return;
            }
            strCode = _strCode;
            Application.Current.Dispatcher.Invoke(new Action(() =>
            {
                if (bOutload == false)
                {
                    GroupMemberModels.RemoveAt(GroupMemberModels.Count - 1);
                }
                groupMemberModels.ForEach(x =>
                {
                    x.Index = GroupMemberModels.Count + 1;
                    GroupMemberModels.Add(x);
                });
                bIsLoading = false;
            }));
            if (GroupMemberModels.Count < infoManage.GetMaxCount(iPage))
            {
                IsLoadFinish = true;
            }
        }

        public bool DoSomeThing()
        {
            if (IsLoadFinish == false)
            {
                bOutload = true;
                while (true) {
                    if (infoManage.GetMaxCount(pageIdx) > GroupMemberModels.Count)
                    {
                        IsLoadFinish = true;
                        bOutload = false;
                        break;
                    }
                    pageIdx++;
                    LoadNoAsync(strCode, pageIdx);
                }
            }
            return true;
        }
    }
}
